package moodish.dummy;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import moodish.comm.MessageFromServer;
import moodish.comm.MessageToServer;
import moodish.comm.ClientSideMessage.Type;

/**
 * 
 * Handler for the server listen and send some message for each client
 */
public class DealWithClient extends Thread {
	/**
	 * In and Out channels for some client
	 * The socket is also saved
	 */
	private ObjectInputStream in;
	private ObjectOutputStream out;
	private Socket socket;
	
	/**
	 * The Server
	 */
	private ServerCommDummy server;
	
	
	/**
	 * DealWithClient Socket
	 * 
	 * @param in InputSocketChannel
	 * @param server ServerCommDummy
	 * @param socket Client Socket
	 * @param out OutputSocketChannel
	 */
	public DealWithClient(ObjectInputStream in, ServerCommDummy server, Socket socket, ObjectOutputStream out) {
		this.in = in;
		this.out = out;
		this.server = server;
		this.socket = socket;
	}

	/**
	 * Thread Running It Will read all messages send from the client to the
	 * server. After Read tell server that has received a message
	 * 
	 * If some error occured try to send a Disconnect message
	 * If can send the error
	 * 
	 * remove this connection
	 */
	@Override
	public void run() {
		super.run();
		
		try {
			// Enquanto estiver activo
			while (!interrupted()) {
				// Vai lendo as mensagens recebidas
				MessageToServer msg = (MessageToServer) in.readObject();
				server.addMessage(msg);				
			}
		} catch (IOException e) {
			// Some sent message was not fromt the type
			// MessageToServer, so end everything
		} catch (ClassNotFoundException e) {
			// Some sent message was not fromt the type
			// MessageToServer, so end everything
		} finally {
			// Always:
			try {
				// try to send a end of connection
				out.writeObject(new MessageFromServer(Type.DISCONNECTED, null));
			} catch (IOException e) {
				// IO Error -> Socket closed in an inaproried way
				// ex: Connection Lost
				// ex: Window closed without disconnect
				
				server.removeClient(this);
				System.out.println("HEY HEY this one will go out!!!");
			}
		}
	}
	
	/**
	 * 
	 * @return object output channel
	 */
	public ObjectOutputStream getOutputStream() {
		return out;
	}
	
	/**
	 * 
	 * @return object input channel
	 */
	public ObjectInputStream getInputStream() {
		return in;
	}
	
	
	
	/**
	 * Shutdown current connection and the message reader
	 */
	public void shutDown(){
		try {
			socket.close();
//			interrupt();
		} catch (IOException e) {
			// Error whole closing the socket
		}
	}

	/**
	 * Checks socket connection
	 * 
	 * @return is socket connect
	 */
	public boolean isConnect() {
		return socket.isConnected();
	}

}
